﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using snat.proxy.items;

namespace snat.proxy.sqlapi {
    public static class ConnectionQuery {

        public static ListProxy<snat.proxy.items.Connection> All(bool isGreedy = true) {
            return Query.SQLQuery<snat.proxy.items.Connection>(
                String.Join(" ", Query.SELECT, Query.ALL, Query.FROM, "Connected", Query.NATURAL_JOIN, 
                                "(", Query.SELECT, Query.EntityID, Query.AS, Query.FromEntityID, ",", Query.EntityName, Query.AS, Query.Sender, 
                                     Query.FROM, Query.Entity, ")", Query.AS, "dummy1", Query.NATURAL_JOIN, 
                                "(", Query.SELECT, Query.EntityID, Query.AS, Query.ToEntityID, ",", Query.EntityName, Query.AS, Query.Recipient,
                                     Query.FROM, Query.Entity, ")", Query.AS, "dummy2"), isGreedy);
        }

        public static ListProxy<Connection> Init(bool isGreedy = true) {
            return Query.SQLQuery<snat.proxy.items.Connection>(
                String.Join(" ", Query.SELECT, Query.ALL, Query.FROM, "Connected", Query.NATURAL_JOIN,
                                "(", Query.SELECT, Query.EntityID, Query.AS, Query.FromEntityID, ",", Query.EntityName, Query.AS, Query.Sender,
                                     Query.FROM, Query.Entity, ")", Query.AS, "dummy1", Query.NATURAL_JOIN,
                                "(", Query.SELECT, Query.EntityID, Query.AS, Query.ToEntityID, ",", Query.EntityName, Query.AS, Query.Recipient,
                                     Query.FROM, Query.Entity, ")", Query.AS, "dummy2",
                                 Query.WHERE, Query.Initial, Query.EQUALS, Query.TRUE), isGreedy);
        }

        public static ListProxy<snat.proxy.items.Connection> ByEntityID(int id, bool isGreedy = false) {
            return Query.SQLQuery<snat.proxy.items.Connection>(@"SELECT * FROM Connected 
                                                       WHERE ToEntityID = " +id+" OR FromEntityID = "+id, isGreedy);
        }

        public static ListProxy<snat.proxy.items.Connection> Between(int fromID, int toID, bool directed = true, bool isGreedy = false) {
            if (directed) {
                return Query.SQLQuery<snat.proxy.items.Connection>(@"SELECT * FROM Connected
                                                          WHERE ToEntityID = " + toID + " AND FromEntityID = " + fromID, isGreedy);
            } else {
                return Query.SQLQuery<snat.proxy.items.Connection>(@"SELECT * FROM Connected
                                                      WHERE (ToEntityID = " + toID + " AND FromEntityID = " + fromID + @")
                                                      OR (ToEntityID = " + fromID + " AND FromEntityID = " + toID + ")", isGreedy);
            }
        }

    }
}
